package com.zmzncs.lmtc.common.util;




import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.zmzncs.lmtc.common.pojo.PageInfo;
import com.zmzncs.lmtc.module.order.pojo.order_Info.OrderInfoDTO;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 转换类
 */
public class JsonUtil {

    public static final String serializeAllExcept = "serializeAllExcept";
    public static final String filterOutAllExcept = "filterOutAllExcept";

    /**
     * 对象转
     */
    public static <T> String objectToJson(T T){
        String json="";
        try {
            ObjectMapper jsonMapper = new ObjectMapper();
            jsonMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            json = jsonMapper.writeValueAsString(T);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 将json转化为实体POJO
     */
    public static <T> T JSONToObj(String jsonStr, Class<T> T) {
        T t = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            t = objectMapper.readValue(jsonStr, T);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 返回json 节点
     */
    public static JsonNode getJsonNode(String jsonStr) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            return objectMapper.readTree(jsonStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回json的value
     */
    public static String getJsonValue(JsonNode node, String key) {
        JsonNode result =node.get(key);
        if(result!=null){
            if(result.getNodeType().name().equalsIgnoreCase("STRING")){
                return result.asText();
            }else {
                return result.toString();
            }
        }
        return null;
    }

    /**
     *  过滤字段
     *  filterName需要跟类上的注解@JsonFilter("xxx")里面的一致
     *  beanProperties过滤的字段
     *  serializeAllExcept 表示序列化全部，除了指定字段
     *  filterOutAllExcept 表示过滤掉全部，除了指定的字段
     */
    /**
     * 过滤字段
     * @param filterName 需要跟类上的注解@JsonFilter("xxx")里面的一致
     * @param beanProperties 过滤的字段
     * @param type  serializeAllExcept 表示序列化全部，除了指定字段。 filterOutAllExcept 表示过滤掉全部，除了指定的字段。
     *
     */
    public static ObjectMapper setupJsonFilter(String filterName, String[] beanProperties, String type){
        if(StringUtils.isBlank(filterName) || StringUtils.isAnyBlank(beanProperties) ){
            ObjectMapper mapper = new ObjectMapper();
            try {
                mapper.writeValueAsString("缺少参数");
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return mapper;
        }

        ObjectMapper mapper = new ObjectMapper();
        //serializeAllExcept 表示序列化全部，除了指定字段。
        if(type.equals(JsonUtil.serializeAllExcept)){
            FilterProvider filterProvider = new SimpleFilterProvider()
                    .addFilter(filterName, SimpleBeanPropertyFilter.serializeAllExcept(beanProperties));

            mapper.setFilterProvider(filterProvider);
            return mapper;
        }
        // filterOutAllExcept 表示过滤掉全部，除了指定的字段。
        if(type.equals(JsonUtil.filterOutAllExcept)){
            FilterProvider filterProvider = new SimpleFilterProvider()
                    .addFilter(filterName, SimpleBeanPropertyFilter.filterOutAllExcept(beanProperties));

            mapper.setFilterProvider(filterProvider);
            return mapper;
        }
        //  type不对
        try {
            mapper.writeValueAsString("type只能是serializeAllExcept或者filterOutAllExcept");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return mapper;
    }

    /**
     * list泛型转型
     */
    public static <T> List<T> listTransform(List oldList, Class<T> beanType){
        ObjectMapper objectMapper = new ObjectMapper();
        // 解决jackson2无法反序列化LocalDateTime的问题
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        // ObjectMapper忽略未知字段，相当于@JsonIgnoreProperties(ignoreUnknown = true)
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        List<T> list = new ArrayList<>();
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
            String jsonData = objectMapper.writeValueAsString(oldList);
            list = objectMapper.readValue(jsonData, javaType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 分页数据类型转型
     */
    public static <T> PageInfo<T> pageTransform(IPage iPage, Class<T> beanType) {
        //  转化分页数据
        List<T> list = new ArrayList<>();
        for(Object object: iPage.getRecords()){
            //  Feature.OrderedField：保持顺序
            T t = JSONObject.parseObject(JSON.toJSONString(object), beanType, Feature.OrderedField);
            list.add(t);
        }

        //  新分页数据
        PageInfo pageInfo = new PageInfo();
        pageInfo.setCurrent((int) iPage.getCurrent());
        pageInfo.setPages((int) iPage.getPages());
        pageInfo.setSize((int) iPage.getSize());
        pageInfo.setTotal((int) iPage.getTotal());
        pageInfo.setRecords(list);

        return pageInfo;
    }

    public static <T> T objectTransform(OrderInfoDTO t1, Class<T> beanType){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        // ObjectMapper忽略未知字段，相当于@JsonIgnoreProperties(ignoreUnknown = true)
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        String jsonStr = null;
        T  detail = null;
        try {
            jsonStr = objectMapper.writeValueAsString(t1);
            detail = objectMapper.readValue(jsonStr , beanType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return detail;
    }

    public static void  main(String[] args){
        String s = "{\"addresslist-explorer\":{\"result\":{},\"query\":{\"display-name\":\"3333\"}}}";
        JsonNode node = JsonUtil.getJsonNode(s);
        JsonNode node1 = JsonUtil.getJsonNode(JsonUtil.getJsonValue(node,"addresslist-explorer"));
        System.out.println(JsonUtil.getJsonValue(node,"addresslist-explorer"));
        System.out.println(JsonUtil.getJsonValue(node1,"result"));
    }

}
